<?php
namespace App\Http\Controllers\Service;

use App\Http\Controllers\Controller;
use App\Models\M3Result;
use Illuminate\Http\Request;
use App\Entity\CartItem;
/**
 *
 */
class CartController extends Controller
{
    //加入购物车
    public function addCart(Request $request,$product_id)
    {
        $bk_cart = $request->cookie('bk_cart');
        $bk_cart_arr = ($bk_cart != null ? explode(',',$bk_cart) : array());
//        return $bk_cart_arr;
        $count = 1;
        foreach ($bk_cart_arr as &$value){//一定要传引用
            //获取冒号早字符串中的位置
            $index = strpos($value,':');
            if(substr($value,0,$index)==$product_id) {
              $count = ((int) substr($value,$index + 1)) + 1;
              $value = $product_id.':'.$count;
              break;
            }
        }
        //如果还是等于1 说明是第一次添加
        if($count == 1){
            array_push($bk_cart_arr,$product_id.':'.$count);
        }
//        return $bk_cart_arr;
        $m3_result = new M3Result;
        $m3_result->status = 0;
        $m3_result->massage = '添加成功';

        return response( $m3_result->toJson())->withCookie('bk_cart',implode(',',$bk_cart_arr));
    }

    //购物车页面删除商品
    public function deleteCart(Request $request)
    {
        $m3_result = new M3Result;

        $product_ids = $request->get('product_ids','');
        if($product_ids == '') {
            $m3_result->status = 1;
            $m3_result->status = '未选择商品';
            return $m3_result->toJson();
        }
        $product_ids_arr = explode(',',$product_ids);
        $bk_cart = $request->cookie('bk_cart');
        $bk_cart_arr = ($bk_cart != null ? explode(',',$bk_cart):array());
        foreach ($bk_cart_arr as $key => $value) {
            $index = strpos($value,':');
            $product_id = substr($value,0 ,$index);
            //判断,删除
            if(in_array($product_id,$product_ids_arr)){
                array_splice($bk_cart_arr,$key,1);
                continue;
            }
        }

        $m3_result->status=0;
        $m3_result->messqge = '删除成功';

        return response( $m3_result->toJson())->withCookie('bk_cart',implode(',',$bk_cart_arr));


    }
}